<template>
    <div>
        <Headline :headline1="$t('m.FaceRecognition')+'  /  '" :headline2="$t('m.PermissionGroupBindPersonnel')"/>
        <a-card>
            <div class="search-a ov_flex">
                <a-input-search
                        :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                        style="width: 200px"
                        v-model="forminitial.key"
                        @search="onSearch"
                />
            </div>
            <a-table
                    size="small"
                    style="margin-top: 30px; margin-bottom: 15px"
                    :columns="columns"
                    :rowKey="(record, i) => i"
                    :data-source="data"
                    :pagination="false"
                    bordered
            >
                <div slot="tag" slot-scope="text, tag, i">
                    <a-button type="primary" @click="addauths(text, tag, i)"
                              style="margin-right:15px"
                              :disabled="!isTrue('face:group:access:add')"
                    >{{$t('m.TheNewAuthorization')}}
                    </a-button
                    >
                    <a-button type="primary" @click="show(text, tag, i)">{{$t('m.Examine')}}</a-button>
                </div>
            </a-table>
            <a-pagination
                    class="pages"
                    show-size-changer
                    :defaultPageSize="5"
                    :default-current="1"
                    :total="totals"
                    @change="elPages"
                    :pageSizeOptions="['5', '10', '30', '40']"
                    @showSizeChange="elShowpowerChange"
            />
        </a-card>
        <a-modal
                :title="$t('m.PermissionGroupPersonInfo')"
                :visible="visible"
                @cancel="handleCancel"
                width="1200px"
                :cancelText="$t('m.Cancel')"
                :okText="$t('m.Ok')"
        >
            <a-input-search
                    v-model="personnfrom.key"
                    :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                    style="width:200px;margin-right:15px;"
                    enter-button @search="onSearchA"/>
            {{$t('m.DownloadStatus')}}：
            <a-select
                    v-model="personnfrom.downStatus"
                    @change="celete"
                    style="width: 120px;margin-right:15px;"
            >
                <a-select-option v-for="item in dictionariesA" :value="item.code" :key="item.code">{{item.name}}
                </a-select-option>
            </a-select>
            {{$t('m.NatureOfPersonnel')}}：
            <a-select
                    v-model="personnfrom.property"
                    @change="celete"
                    style="width: 120px;margin-right:15px;"
            >
                <a-select-option value="-1"> 全部</a-select-option>
                <a-select-option value="0"> 临时员工</a-select-option>
                <a-select-option value="1"> 正式员工</a-select-option>
            </a-select>
            {{$t('m.Equipment')}}：
            <a-select
                    v-model="personnfrom.devId"
                    @change="celete"
                    style="width: 120px;margin-right:15px;"
            >
                <a-select-option value="0"> 全部</a-select-option>
                <a-select-option value="11"> 人脸识别机</a-select-option>
                <a-select-option value="47"> 人脸识别</a-select-option>
            </a-select>
            <a-button type="primary"
                      v-if="isTrue('face:group:access:redown')"
                      style="margin-right:15px;" @click="download">{{$t('m.ReDownload')}}
            </a-button>
            <a-button type="primary" v-if="isTrue('face:group:access:del')"
                      @click="removeauth">{{$t('m.DeleteTheAuthorized')}}
            </a-button>
            <a-table
                    style="margin-top: 30px"
                    :columns="columnsB"
                    :rowKey="(record, i) => i"
                    :data-source="dataB"
                    :pagination="false"
                    bordered
                    :row-selection="{
          onChange: bindSelectChange,

          selectedRowKeys: bindsclete,
        }"
            >
                <div slot="status" slot-scope="text,tag">
                    <a v-if="tag.downstatusname=='已下载'" class="colorGreen">
                        {{tag.downstatusname}}
                    </a>
                    <a v-else-if="tag.downstatusname=='待下载'||
        tag.downstatusname=='待重下'"
                       class="colorBlue">
                        {{tag.downstatusname}}
                    </a>
                    <a v-else class="colorRed">{{tag.downstatusname}}</a>
                </div>
                <!-- <a class="fontColor" @click="a(text)">

                </a> -->
            </a-table>
            <a-pagination
                    class="pages"
                    show-size-changer
                    :defaultPageSize="5"
                    :default-current="1"
                    :total="total"
                    @change="bindPages"
                    :pageSizeOptions="['5', '10', '30', '40']"
                    @showSizeChange="bindShowpowerChange"
            />
        </a-modal>
        <a-modal
                :title="$t('m.TheNewAuthorization')"
                width="1000px"
                :visible="authvis"
                @cancel="authShow"
                @ok="authOks"
                :cancelText="$t('m.Cancel')"
                :okText="$t('m.Ok')"
        >
            <div class="row-col">
                <a-tree-select
                        v-model="value"
                        show-search
                        style="width: 30%;"
                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                        placeholder="Please select"
                        allow-clear
                        @change="bindchecked"
                        tree-default-expand-all
                >

                    <a-tree-select-node
                            v-for="item in items"
                            :key="item.id"
                            :cont="item"
                            :value="item.custorgname"
                            :title="item.custorgname"
                    >
                        <a-tree-select-node
                                v-for="int in item.children"
                                :key="int.id"
                                :cont="int"
                                :value="int.custorgname"
                                :title="int.custorgname"
                        >
                            <a-tree-select-node
                                    v-for="ins in int.children"
                                    :key="ins.id"
                                    :cont="ins"
                                    :value="ins.custorgname"
                                    :title="ins.custorgname"
                            />
                        </a-tree-select-node>
                    </a-tree-select-node>
                </a-tree-select>
                <a-input-search
                        :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                        style="width: 200px;margin-left: 15px"
                        v-model="infolist.key"
                        @search="onbindSearch"
                />
                <div class="chend">
                    <a-checkbox :defaultChecked="infolist.vChild" @change="textChange">
                        {{$t('m.WhetherToDisplayChildNodes')}}
                    </a-checkbox>
                </div>
            </div>
            <a-transfer
                    style=" margin-top: 15px;"
                    :locale="{itemUnit: '项',itemsUnit: '项'}"
                    :titles="['未选人员', '已选人员']"
                    :data-source="mockData"
                    :target-keys="targetKeys"
                    :disabled="disabled"
                    :show-search="showSearch"
                    :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
                    :show-select-all="false"
                    @change="onChange"
            >
                <template
                        slot="children"
                        slot-scope="{
          props: { direction, filteredItems, selectedKeys},
          on: { itemSelectAll, itemSelect },
        }"
                >
                    <a-table
                            :row-selection="
            getRowSelection({ selectedKeys,
             itemSelectAll, itemSelect })
          "
                            :columns="direction === 'left' ? leftColumns : rightColumns"
                            :data-source="filteredItems"
                            :pagination="direction === 'left'?ipagination:Rightipagination"
                            bordered
                    />
                </template>
            </a-transfer>
        </a-modal>
        <Delete ref="bindel" :dalete="dalete" @confirm="bindok"/>
        <Delete ref="bindownload" :dalete="huadalete" @confirm="bindownload"/>
    </div>
</template>

<script>
    import Headline from "@/components/Headline";
    import Delete from "@/components/Delete";
    import difference from "lodash/difference";
    import {
        getAuthGroupList,
        getDelGroupAccess,
        getGroupAccessList,
        getRedown,
        saveGroupAccess
    } from "@/api/faceRecognition";
    import {getPerages, getStaff} from "@/api/perAges";
    import {Setperms} from '@/assets/js/setperms'
    import {getdiction} from "@/api/dictionaries";


    const mockData = [];
    const originTargetKeys = [];
    const leftTableColumns = [
        {title: "工号", dataIndex: "stafforstucode"},
        {title: "名称", dataIndex: "stafforstuname"},
        {title: "性别", dataIndex: "sex"},
        {title: "所属单位", dataIndex: "orgname"},
    ];
    const rightTableColumns = [
        {title: "名称", dataIndex: "stafforstuname"},
        {title: "所属单位", dataIndex: "orgname"},
    ];
    export default {
        name: "BindingPersonnel",

        components: {Headline, Delete},
        data() {
            return {
                ipagination: {
                    defaultPageSize: 5,
                    pageSizeOptions: ['5', '10', '20'],
                    showSizeChanger: true,
                    // showQuickJumper:true,
                    onShowSizeChange: this.pageSizeChange,
                    onChange: this.pageChange,
                    total: 0
                },
                Rightipagination: {
                    defaultPageSize: 5,
                },
                mockData,
                targetKeys: originTargetKeys,
                selectedKeys: [],
                showSearch: false,
                disabled: false,
                leftColumns: leftTableColumns,
                rightColumns: rightTableColumns,
                forminitial: {
                    start: 0,
                    limit: 20,
                    key: "",
                    page: 1,
                },
                direction: "",
                dalete: {
                    titles: this.$t('m.DeleteThePrompt'),
                    type: "exclamation-point",
                    text: this.$t('m.AreYouSureToDeleteData'),
                },
                huadalete: {
                    titles: this.$t('m.DownloadPrompt'),
                    type: "exclamation-point",
                    text: this.$t('m.AreYouSureToReDownload'),
                },
                data: [],
                columns: [
                    {title: this.$t('m.PermissionGroupNumber'), dataIndex: "groupIndex"},
                    {title: this.$t('m.PermissionGroupName'), dataIndex: "groupName"},
                    {title: this.$t('m.WeekPlanName'), dataIndex: "d"},
                    {title: this.$t('m.Operation'), dataIndex: "f", scopedSlots: {customRender: "tag"}},
                ],
                total: 0,
                columnsB: [
                    {title: this.$t('m.DownloadStatus'), dataIndex: "e", scopedSlots: {customRender: "status"}},
                    {title: this.$t('m.EquipmentNumber'), dataIndex: "machineid"},
                    {title: this.$t('m.EquipmentName'), dataIndex: "devname"},
                    {title: this.$t('m.PermissionGroupName'), dataIndex: "groupname"},
                    {title: this.$t('m.Name'), dataIndex: "stafforstuname"},
                    {title: this.$t('m.Learntoworknumber'), dataIndex: "stafforstucode"},
                    {title: this.$t('m.department'), dataIndex: "custorgname"},
                    {title: this.$t('m.DownloadNumber'), dataIndex: "downnum"},
                    {title: this.$t('m.DownloadTime'), dataIndex: "downtime"},
                    {title: this.$t('m.DownloadInfo'), dataIndex: "downstatus"},
                ],
                dataB: [],
                visible: false,
                personnfrom: {
                    groupId: 0,
                    downStatus: "-1",
                    key: "",
                    property: "-1",
                    devId: "0",
                    start: 0,
                    limit: 10,
                    page: 1,
                },
                total: 0,
                bindsclete: [],
                downloads: "",
                devauth: {
                    delIds: "",
                    waitDelIds: "",
                },
                totals: 0,
                authvis: false,
                items: [],
                formunitdata: {
                    orgType: 1,
                    key: "",
                },
                value: "",
                fromcode: {
                    groupId: 0,
                    ymOrgTreeCode: "",
                    infoType: 0,
                    property: -1,
                    viewChild: true,
                    isHasModel: 1,
                    selectedIds: "",
                    page: 1,
                    start: 0,
                    limit: 50,
                },
                infolist: {
                    ymOrgTreeCode: "",
                    infoType: 1,
                    status: 1,
                    vChild: true,
                    key: "",
                    start: 0,
                    limit: 5,
                    property: -1,
                    page: 1,
                },
                setsclete: [],
                anthIdfrom: {
                    groupId: 0,
                    ids: ""
                },
                transfertotal: 0,
                colorBlue: 'colorBlue',
                colorRed: 'colorRed',
                fromdic: {
                    groupcode: "SYS0000025",
                    insertall: "-1|全部",
                    where: "code<> -1 and code <> -100",
                },
                dictionariesA: [],

            };
        },
        created() {
            this.getGroupList();
            this._getPerages();
            this.parms = Setperms(this.$route.fullPath, JSON.parse(sessionStorage.getItem('menu')))
            console.log(this.parms)
            this._getdiction();

        },
        methods: {
            _getdiction() {
                getdiction({params: this.fromdic}).then((res) => {
                    console.log(res);
                    this.dictionariesA = res.data.data;
                });

            },
            pageSizeChange(val, pageNum) {
                console.log(val, pageNum)
                this.infolist.limit = pageNum
                this.infolist.page = val
                this.infolist.start = pageNum * (val - 1)
                this._getStaff()

            },
            pageChange(page, val) {
                this.infolist.page = page
                this.infolist.limit = val
                this.infolist.start = (page - 1) * val
                this._getStaff()
                console.log(page, val)

            },
            onSearchA() {
                this._getGroupAccessList()
            },
            isTrue(str) {
                return this.parms.indexOf(str) !== -1;
            },
            //获取权限组信息
            getGroupList() {
                getAuthGroupList({params: this.forminitial})
                    .then((res) => {
                        this.data = res.data.data;
                        this.totals = res.data.total;
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            },
            //请求授权数据
            _getPerages() {
                getPerages({params: this.formunitdata})
                    .then((res) => {
                        console.log(res);
                        if (res.data) {
                            this.items = res.data;
                            this.$message.success("获取单位数据成功");
                        }
                    })
                    .catch((err) => {
                        this.$message.error("获取单位数据失败");
                    });
            },
            //请求表单数据
            _getStaff() {
                getStaff({params: this.infolist}).then((res) => {
                    this.transfertotal = res.data.total;
                    this.ipagination.total = res.data.taotal
                    this.mockData = res.data.data.map((item) => {
                        return {
                            title: item.orgname,
                            key: item.id + '',
                            disabled: false,
                            stafforstucode: item.stafforstucode,
                            stafforstuname: item.stafforstuname,
                            sex: item.sex == "1" ? "男" : "女",
                            orgname: item.orgname

                        };
                    });
                });
            },
            show(text, tag, i) {
                this.visible = true;
                console.log(tag);
                this.personnfrom.groupId = tag.groupId;
                this._getGroupAccessList();
            },
            _getGroupAccessList() {
                getGroupAccessList({params: this.personnfrom}).then((res) => {
                    console.log(res);
                    this.dataB = res.data.data;
                    this.total = res.data.total;
                });
            },
            onsChange() {
            },
            //取消弹窗
            handleCancel() {
                this.bindsclete = [];
                this.visible = false;
            },
            //搜索
            onSearch() {
                this.getGroupList();
            },
            //切换
            celete() {
                this._getGroupAccessList();
            },
            //reodo
            bindSelectChange(text, tag) {
                let accessidList = []
                let downList = []
                console.log(text, tag[0]);
                this.bindsclete = text;

                tag.forEach(item => {
                    accessidList.push(item.accessid)
                    downList.push(item.accessid)
                })
                this.devauth.delIds = accessidList.join(',');
                this.downloads = accessidList.join(',');
            },
            //删除授权
            removeauth() {
                if (this.bindsclete.length > 0) {
                    this.$refs.bindel.visible = true;
                } else {
                    this.$message.error("请选择数据");
                }
            },
            //删除弹窗确定
            bindok() {
                getDelGroupAccess(this.devauth)
                    .then((res) => {
                        const msg = res.data.msg;
                        if (res.data.success) {
                            this.$message.success(msg);
                            this.bindsclete = [];
                            this._getGroupAccessList();
                        } else {
                            this.$message.error(msg);
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                this.$refs.bindel.visible = false;
            },
            //重新下载
            download() {
                if (this.bindsclete.length > 0) {
                    this.$refs.bindownload.visible = true;
                } else {
                    this.$message.error("请选择数据");
                }
            },
            //重新下载中弹窗确定
            bindownload() {
                getRedown({accessIds: this.downloads})
                    .then((res) => {
                        console.log(res)
                        const msg = res.data.msg;
                        if (res.data.success) {
                            this.$message.success(msg);
                            this.bindsclete = [];
                            this._getGroupAccessList();
                        } else {
                            this.$message.error(msg);
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                this.$refs.bindownload.visible = false;
            },
            //新增授权
            addauths(text, tag, i) {
                console.log(tag);
                this.anthIdfrom.groupId = tag.groupId
                this.authvis = true;
                this._chexd();
            },
            //取消授权弹窗
            authShow() {
                this.authvis = false;
                this.targetKeys = []
            },
            //确定
            authOks() {
                saveGroupAccess(this.anthIdfrom).then(res => {
                    if (res.data.success == true) {
                        this.$message.success('新增授权成功')
                    } else {
                        this.$message.warning(res.data.msg)
                    }
                })
                    .catch(err => {
                        this.$message.error('操作失败')
                    })
                this.targetKeys = []
                this.authvis = false;
            },
            //选中触发
            bindchecked(value, label, extra) {
                if (extra.triggerNode) {
                    //获取当前选中的对象信息
                    const cont = extra.triggerNode.$attrs.cont;
                    console.log(cont);
                    this.infolist.ymOrgTreeCode = cont.ymorgtreecode;
                    this._getStaff();
                }
            },
            // 默认展示数据
            _chexd() {
                //默认选择第一条数据
                const item = this.items[0];
                this.infolist.ymOrgTreeCode = item.ymorgtreecode;

                this.value = item.custorgname;
                this._getStaff();
            },
            //子节点事件
            textChange() {
                this.infolist.vChild = !this.infolist.vChild
                this._getStaff();
            },
            //授权搜索
            onbindSearch() {
                this._getStaff();
            },
            //穿梭框方法
            triggerShowSearch(showSearch) {
                this.showSearch = showSearch;
                console.log(showSearch)
            },
            onChange(nextTargetKeys, e, a) {
                this.targetKeys = nextTargetKeys;
                console.log(nextTargetKeys, a)
                this.anthIdfrom.ids = nextTargetKeys.join(',');
            },
            triggerDisable(disabled) {
                this.disabled = disabled;
            },
            getRowSelection({disabled, selectedKeys, itemSelectAll, itemSelect}) {
                return {
                    getCheckboxProps: (item) => ({
                        props: {disabled: disabled || item.disabled},
                    }),
                    onSelectAll(selected, selectedRows) {
                        const treeSelectedKeys = selectedRows
                            .filter((item) => !item.disabled)
                            .map(({key}) => key);
                        const diffKeys = selected
                            ? difference(treeSelectedKeys, selectedKeys)
                            : difference(selectedKeys, treeSelectedKeys);
                        itemSelectAll(diffKeys, selected);
                    },
                    onSelect({key}, selected) {
                        console.log(key)
                        itemSelect(key, selected);
                    },
                    selectedRowKeys: selectedKeys,
                };
            },
            //分页
            bindPages(page, limit) {
                console.log(page, limit);
                this.personnfrom.page = page;
                this.personnfrom.limit = limit;
                this.personnfrom.start = (page - 1) * limit;
                this._getGroupAccessList();
            },
            bindShowpowerChange(page, pageSize) {
                this.personnfrom.page = page;
                this.personnfrom.limit = pageSize;
                this.personnfrom.start = (page - 1) * pageSize;
                this._getGroupAccessList();
            },
            elPages(page, limit) {
                console.log(page, limit);
                this.forminitial.page = page;
                this.forminitial.limit = limit;
                this.forminitial.start = (page - 1) * limit;
                this.getGroupList();
            },
            elShowpowerChange(page, pageSize) {
                this.forminitial.page = page;
                this.forminitial.limit = pageSize;
                this.forminitial.start = (page - 1) * pageSize;
                this.getGroupList();
            },
        },
    };
</script>

<style lang="scss" scoped>
    .pages {
        margin-top: 15px;
    }

    .search-a {
        width: 600px;
    }

    .select-a {
        width: 300px;
    }

    .ov_flex {
        display: flex;
        align-items: center;
    }

    .flex-dev {
        display: flex !important;
        justify-content: center;
    }

    .row-col {
        display: flex;
        align-items: center;
    }

    .chend {
        margin-left: 15px;

    }

    .colorRed {
        color: red
    }

    .colorBlue {
        color: blue;
    }

    .colorGreen {
        color: green;
    }
</style>
